package com.cheyun.netsalev3.viewmodel

import android.app.Dialog
import android.content.Context
import android.content.Intent
import android.net.Uri
import android.os.Looper
import android.view.Gravity
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.webkit.WebView
import android.widget.LinearLayout
import androidx.appcompat.app.AlertDialog
import androidx.databinding.ObservableField
import androidx.lifecycle.MutableLiveData
import com.blankj.utilcode.util.ToastUtils
import com.cheyun.netsalev3.MyApplication
import com.cheyun.netsalev3.R
import com.cheyun.netsalev3.bean.Version
import com.cheyun.netsalev3.bean.sys.Prdset
import com.cheyun.netsalev3.repository.LoginRepository
import com.cheyun.netsalev3.utils.FunctionUtils
import com.cheyun.netsalev3.utils.MySharedPreferences
import com.cheyun.netsalev3.utils.ToastUtil
import com.cheyun.netsalev3.utils.api.*
import com.cheyun.netsalev3.utils.api.dm.DmApiCallback
import com.cheyun.netsalev3.utils.api.dm.DmApiException
import com.cheyun.netsalev3.view.*
import com.cheyun.netsalev3.view.stockquery.StockQueryActivity
import com.dou361.dialogui.DialogUIUtils
import com.igexin.sdk.PushManager
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.schedulers.Schedulers
import com.dou361.dialogui.listener.DialogUIListener
import kotlin.reflect.KFunction
import kotlin.reflect.KFunction1


/**
 * @author Michael
 * @date  2018/12/19 - 16:03.
 */
class HomeMyFragmentViewModel : BaseViewModel() {
    var abname = ObservableField<String>("")
    var focus_total = ObservableField<String>("0")
    var realname = ObservableField<String>("")
    var groupname = ObservableField<String>("")
    var mobile = ObservableField<String>("")
    //库存管理
    var statkun = MutableLiveData<Boolean>()
    //客流登记
    var dengji = MutableLiveData<Boolean>()
    //客流接待
    var jiedai = MutableLiveData<Boolean>()
    //战败管理
    var fail = MutableLiveData<Boolean>()

    var showLogOff = ObservableField<Boolean>(false)
    var showLogOffCode = MutableLiveData<Boolean>()
    var loginRepository = LoginRepository()

    lateinit var context: Context
    var xieyi = ApiStores.XIEYI_URL
    init {
        bindData()
    }

    fun bindData(){
        dengji.postValue(false)
        jiedai.postValue(false)
        statkun.postValue(false)
        fail.postValue(false)

        var loginData = MySharedPreferences.getLoginData()
        loginData?.apply {
            var tabname = this?.channel?.abname
            abname.set(tabname)
            var tmobile = this.member.mobile
//            if (!tmobile.isNullOrBlank() && tmobile.length > 7) {
//                tmobile = tmobile.substring(0, 3) + "****" + tmobile.substring(tmobile.length - 4)
//            }
            var trealname = this.member.realname
            mobile.set(tmobile)
            realname.set(trealname)

            var gn = loginData?.member?.groupname
            if(gn == null || gn.isEmpty()){
                if(loginData?.member?.isadmin == 1)
                    gn = "(系统管理员)"
            }else{
                gn = "("+groupname+")"
            }
            groupname.set(gn)

            focus_total.set(this?.member.focus_total)
        }

        var start = loginData?.channel?.settings?.storage?.state ?: 0
        loginData?.member?.apps?.stock?.apply {
            for (i in this) {
                if (i == 1 && start == 1) {
                    statkun.postValue(true)
                }
            }
        }
        loginData?.channel?.settings?.storage?.state?.apply {
            statkun.postValue(this == 1)
        }
        loginData?.member?.apps?.receive?.apply {
            for (i in this) {
                if (i == 1) {
                    dengji.postValue(true)
                }
                if (i == 2) {
                    jiedai.postValue(true)
                }
            }
        }
        loginData?.member?.apps?.chance?.apply {
            for (i in this) {
                if (i.equals("1401")){
                    fail.postValue(true)
                }
            }
        }

        loginData?.member?.isadmin?.apply {
            if(this==1){
                dengji.postValue(true)
                jiedai.postValue(true)
                statkun.postValue(true)
                fail.postValue(true)
            }
        }
        loginData?.channel?.settings?.receive?.apply {
            if(this == 1){
                jiedai.postValue(false)
            }
        }
    }

    fun getprdset(){
        loginRepository.getPrdset(this::setPrdset)
    }
    fun setPrdset(list: List<Prdset>) {
        for(set in list){
            if(set.ikey.equals("delaccount")){
                if(set.isopen.equals("1")){
                    showLogOff.set(true)
                }
            }
        }
    }

    fun checkJiedai(){
        var loginData = MySharedPreferences.getLoginData()
        loginData?.channel?.settings?.receive?.apply {
            var show = true
            if(this == 1){
                show = false
            }
            jiedai.postValue(show)
        }
    }

    /**
     * 点击更多切换经销商
     */
    fun onClickDistributor(view: View) {
        view.context.startActivity(Intent(view.context, SwitchingDealersActivity::class.java))
    }

    fun onClickImportment(view:View){
        MyToast("正在开发中")
    }

    fun onCLickChangePwd(view:View){
        view.context.startActivity(Intent(view.context, ChangePwdActivity::class.java))
    }

    /**
     * 绑定经销商
     */
    fun onClickBindDistributor(view: View) {
        view.context.startActivity(Intent(view.context, BindDistributorActivity::class.java))
    }

    /**
     * 客服中心
     */
    fun kefu(view: View) {
        view.context.startActivity(Intent(view.context, CustomerServiceCenterActivity::class.java))
    }

    fun onClickLog(view: View) {
        var intent = Intent(view.context, H5Activity::class.java)
//        intent.putExtra("url", GlobalConfig.CRM_ANALYSIS_URL+GlobalConfig.UPDATE_LOG)
        view.context.startActivity(intent)
    }

    /**
     * 设置
     */
    fun onClickSet(view: View) {
        view.context.startActivity(Intent(view.context, UserSettingActivity::class.java))
//        view.context.startActivity(Intent(view.context, SetActivity::class.java))

    }


    fun onClickMessage(view: View) {
        view.context.startActivity(Intent(view.context, NewsSetActivity::class.java))
    }


    fun onClickModule(view: View) {
        view.context.startActivity(Intent(view.context, ModuleActivity::class.java))
    }

    fun loginOut(view:View){
        //退出删除别名
        //极光
//        JPushInterface.deleteAlias(view.context,1)
        var uid = MySharedPreferences.getLoginData()?.member?.uid ?: 0
        //个推
        PushManager.getInstance().unBindAlias(view.context, uid.toString(), true)
//        //厂商通道
//        NoticeApiClient.getInstance().deleteFactoryAlias(DmApiStores.NOTICE_APP_ID,DmApiStores.NOTICE_APP_KEY,
//                MyApplication.getInstance().getThirdCode(),uid.toString())
//                .subscribeOn(Schedulers.io())
//                .subscribeOn(AndroidSchedulers.mainThread())
//                .subscribe(object : DmApiCallback<DmBaseResp<Any, Any>>() {
//                    override fun onSuccess(t: DmBaseResp<Any, Any>) {
//
//                    }
//
//                    override fun onError(ex: DmApiException) {
//
//                    }
//                })
        MySharedPreferences.clearAll()

        MyApplication.getInstance().removeActivity(MainActivity::class.java)
        var intent = Intent(view.context, LoginActivity::class.java)
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP)
        view.context.startActivity(intent)
        MyToast("退出成功")
    }

    var currentView:View? = null

    fun onClickLogoff(view:View){
        currentView = view
        var dialog = AlertDialog.Builder(view.context)
                .setTitle("账户注销")
                .setMessage("注销账户将删除您的所有相关数据，并且无法撤销，确认注销吗？")
                .setPositiveButton("注销"){ dialog, which ->  showConfrimLogOff(view) }
                .setNegativeButton("取消") { dialog, which ->  }
                .show()
        FunctionUtils.setAlertDialogPos(dialog)
    }

    fun showConfrimLogOff(view:View){
        loginRepository.getPhoneCode("delAccount", "send", MySharedPreferences.getMobile(),this::setCode )
    }

    fun onClickCheck(view: View) {
        context = view.context
        var currentVersion = FunctionUtils.getCurrentVersion(view.context)
        loginRepository.getVersion(currentVersion, "android", this::setVersion)
    }

    fun setCode(param: Any) {
        ToastUtil.showToast("短信验证码已发送")
        showLogOffCode.postValue(true)
    }
    fun confirmLogOff(view:View,smsCode:String){
        var logoff: () -> Unit = {
            loginOut(view)
        }
        loginRepository.delaccount(MySharedPreferences.getLoginData()?.member?.mid.toString(),MySharedPreferences.getMobile(),smsCode,logoff)
    }

    fun setVersion(data: Version) {
        if (data.update == 0) {
//            Looper.prepare()
            ToastUtils.showLong("当前已是最新版本")
//            Toast.makeText(MyApplication.getInstance(),"当前已是最新版本", Toast.LENGTH_SHORT).show()
//            Looper.loop()
        } else {
            var url = ApiStores.DOWN_URL + data.version + ".apk"
            if(Looper.myLooper()==null)
                Looper.prepare()
            if (data.update == 2) {

            } else {
                var dialog = AlertDialog.Builder(context)
                        .setTitle("更新提示")
                        .setMessage("有新的版本，是否前往更新")
                        .setPositiveButton("是") { dialog, which -> openApk(url, data.version) }
                        .setNegativeButton("否") { dialog, which ->  }
                        .show()
                FunctionUtils.setAlertDialogPos(dialog)
            }
            Looper.loop()
        }
    }

    fun openApk(url: String, version: String) {
        var intent = Intent()
        intent.setData(Uri.parse(url))
        intent.setAction(Intent.ACTION_VIEW)
        context.startActivity(intent)
    }

    /**
     * 七日强转
     */
    fun onClickQiang(view: View) {
        var intent = Intent(view.context, OverdueActivity::class.java)
        //逾期state：1 七日强转2
        intent.putExtra("state", 2)
        view.context.startActivity(intent)
    }

    fun showYs(view:View){
        val bottomDialog = Dialog(view.context, R.style.BottomDialog)
        val contentView = LayoutInflater.from(view.context).inflate(R.layout.dialog_content_circle, null)
        bottomDialog.setContentView(contentView)
        val params = contentView.getLayoutParams() as ViewGroup.MarginLayoutParams
        params.width = view.context.getResources().getDisplayMetrics().widthPixels - FunctionUtils.dip2px(view.context, 16f)
        params.topMargin = FunctionUtils.dip2px(view.context, 20f)
        params.bottomMargin = FunctionUtils.dip2px(view.context, 20f)
        contentView.setLayoutParams(params)
        bottomDialog.getWindow().setGravity(Gravity.BOTTOM)
        bottomDialog.getWindow().setWindowAnimations(R.style.BottomDialog_Animation)
        bottomDialog.show()

        var llWin = contentView.findViewById<LinearLayout>(R.id.ll_win)
        llWin.setOnClickListener { bottomDialog.dismiss() }
    }

}